import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { JSONEditorComponent } from 'ngx-jsoneditor';
import { NzMessageService } from 'ng-zorro-antd';
import { NzNotificationService } from 'ng-zorro-antd';
import { NzModalService } from 'ng-zorro-antd';

import { ConfigmanageService, AppConfig } from '../../../DM/configmange.service';
import { AppManageService, App } from '../../../DM/appmanage.service';

@Component({
  selector: 'app-configuration-management',
  templateUrl: './configuration-management-ls.component.html',
  styleUrls: ['./configuration-management-ls.component.css']
})
export class ConfigurationManagementLsComponent implements OnInit {

  // 组件 https://github.com/devmark/ngx-jsoneditor
  _app: App = new App;
  _appConfigLs: AppConfig[] = [];
  _isDataLoading: boolean = false;

  _newCofig: JSON = JSON.parse(JSON.stringify({}));
  _editorCofig: JSON = JSON.parse(JSON.stringify({}));
  _selectedKey: string;
  // 模态框
  _isConfirmLoading: boolean = false;
  // 模态框 -- 新建
  _isVisible_create: boolean = false;
  // 模态框 -- 编辑
  _isVisible_update: boolean = false;
  // 编辑器
  @ViewChild('updateModal') _updateModal: JSONEditorComponent;
  //搜索
  _searchKey: string;
  _copyData: AppConfig[] = [];
  //keyform
  _configNameForm: FormGroup;

  constructor(
    private configmanageService: ConfigmanageService,
    private appManageService: AppManageService,
    private activatedRoute: ActivatedRoute,
    private msgService: NzMessageService,
    private noticeService: NzNotificationService,
    private confirmServ: NzModalService,
    private fb: FormBuilder
  ) {
    this._configNameForm = fb.group({
      'key': ['', [Validators.required]]
    });
  }

  async ngOnInit() {
    this.activatedRoute.params.subscribe(async (res: { id }) => {
      this._app = await this.appManageService.getAppById(res.id);
      this._isDataLoading = true;
      this._appConfigLs = await this.configmanageService.getAppConfigAllItems(res.id);
      this._copyData = [...this._appConfigLs];
      this._isDataLoading = false;
    });
  }

  // 点击更新按钮
  update(value: JSON, key: string) {
    this._isVisible_update = true;
    this._editorCofig = value;
    this._selectedKey = key;
  }

  // 删除配置项
  _delete(key: string) {
    this.confirmServ.confirm({
      title: 'Delete config',
      content: '<b>This operation will lead to the deletion of the data could not be resumed, confirmed to delete?</b>',
      okText: 'delete',
      cancelText: 'cancel',
      onOk: async () => {
        try {
          await this.configmanageService.deleteConfig(key, this._app.AppId);
          this.msgService.success('delete success');
          this.noticeService.blank('delete config', 'delete config success');
        } catch (err) {
          console.error(err);
          this.msgService.error('delete error');
          this.noticeService.blank('delete config', `because of ${err}，delete config error`);
        }
        this._isDataLoading = true;
        this._appConfigLs = await this.configmanageService.getAppConfigAllItems(this._app.AppId);
        this._isDataLoading = false;
      },
    });
  }

  // 新建取消
  _handleCancel_c(e) {
    this._isVisible_create = false;
  }

  // 新建创建
  async _handleOk_c(e) {
    for (let k in this._configNameForm.controls) {
      this._configNameForm.controls[k].markAsDirty();
    }
    if (!this._configNameForm.valid) { return; }
    this._isConfirmLoading = true;
    try {
      await this.configmanageService.createConfig(
        this._configNameForm.controls['key'].value,
        JSON.stringify(this._newCofig),
        this._app.AppId,
      );
      this._isVisible_create = false;
      this.msgService.success('create success');
      this.noticeService.blank('create config', 'create config success');
      this._isDataLoading = true;
      this._appConfigLs = await this.configmanageService.getAppConfigAllItems(this._app.AppId);
      this._isDataLoading = false;
    } catch (err) {
      console.error(err);
      this.msgService.error('create error');
      this.noticeService.blank('create config', `because of ${err}，create config error`);
    }
    this._isConfirmLoading = false;
  }

  // 编辑取消
  _handleCancel_u(e) {
    this._isVisible_update = false;
  }

  // 编辑创建
  async _handleOk_u(e) {
    this._isConfirmLoading = true;
    try {
      JSON.parse(this._updateModal.getText());
      await this.configmanageService.updateConfig(
        this._selectedKey,
        JSON.stringify(this._editorCofig),
        this._app.AppId
      );
      this._isVisible_update = false;
      this.msgService.success('update success');
      this.noticeService.blank('update config', 'update config success');
      this._isDataLoading = true;
      this._appConfigLs = await this.configmanageService.getAppConfigAllItems(this._app.AppId);
      this._isDataLoading = false;
    } catch (err) {
      console.error(err);
      this.msgService.error('update error');
      this.noticeService.blank('update config', `because of ${err}，update config error`);
    }
    this._isConfirmLoading = false;
  }

  // 搜索
  _search() {
    this._appConfigLs = this._copyData.filter(config => {
      return this._searchKey.length ? config.Key.toLowerCase().indexOf(this._searchKey.toLowerCase()) > -1 : this._copyData;
    });
  }

}
